/**
 * Created by fanxu on 16/4/29.
 */
/**
 *抽奖js
 *Author: Fan Xu
 * 初始化 FX.Prize.init()
 * 摇一摇倒计时时间秒数 FX.Prize.shake_second
 * 用户随机跳动速度 FX.Prize.speed
 * 中奖个数 FX.Prize.prize_count
 * 获取需要随机展示用户列表
 * FX.Prize.users
 * 格式：[{user_id:1,openid:'asfrcdegreh',nickname:'fanxu',name'范旭',avatar:'xsfdsfd.jpg',mobile:'18321408624'},];
 * 获取中奖用户列表
 * FX.Prize.current_prize_persons
 * 格式 [{user_id:1,openid:'asfrcdegreh',nickname:'fanxu',name'范旭',avatar:'xsfdsfd.jpg',mobile:'18321408624'},];
 * 返回中奖用户回调函数
 * FX.Prize.displayEffect = function(){}
 **/
var FX = {};
FX.Prize = {
    cut_persons:[],//内定用户
    users:[],//备用随机符合条件用户
    speed:0,//转动速度
    shake_second:15,//摇一摇倒计时时间
    get_prize_result_url:'calcResult.php',//服务器抽奖给到本地
    send_prize_result_url:'calcRandResult.php',//本地抽奖传回服务器
    start_shake_api:'shakeStatus.php?status=1',//开始摇一摇接口
    close_shake_api:'shakeStatus.php?status=0',//结束摇一摇接口
    type:0,//0服务器抽奖 1本地抽奖
    is_ajax:false,//是否正在请求ajax
    cookie_key:'prizePersons',
    prize_persons:[],//已经获奖用户
    current_prize_persons:[],//当前获奖的用户
    prize_count:1,//中奖的个数
    init:function(o){
        this.cut_persons = o.cut_persons;
        this.users = o.users;
        this.speed = parseInt( $('#speed').text() );
        this.shake_second = parseInt( $('#shake_second').text() );
        this.type = parseInt( $('#prize_type').text() );
        this.prize_count = parseInt( $('#prize_count').text() );
        this.prize_persons = getCookie( this.cookie_key );
        if( this.prize_persons )
            this.prize_persons = this.prize_persons.split(',');
        else{
            this.prize_persons = [];
        }
    },
    randPrize:function(){ //进行抽奖
        if( this.type == 0 ){
            this.serverPrize();
        }
        else{
            this.localPrize();
        }
    },
    serverPrize:function(){
        //服务器抽奖
        var that = this;
        if( that.is_ajax ){
            return false;
        }
        that.is_ajax = true;
        $.ajax({
            url:that.get_prize_result_url,
            type:"post",
            dataType:"json",
            timeout:3000, //3s超时
            data:{},
            error:function(){
                //网络错误
                that.localPrize();
                that.is_ajax = false;
            },
            complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
                if(status=='timeout'){//超时,status还有success,error等值的情况
                    that.localPrize();
                }
            }
        }).done(function(data){
            that.is_ajax = false;
            if( data.error == 0 ){
                $.each(data.data.list,function(k,v){
                    that.prize_persons.push(v.user_id);
                    that.current_prize_persons.push( v );
                });
                if( data.data.list && ( data.data.list.length == data.data.count ) ){
                    setCookie('prizePersons',that.prize_persons.toString());
                    //页面展示获奖用户特效
                    that.displayEffect();
                }
                else{
                    //如果服务器返回的结果不够 则离线抽奖补上
                    that.localPrize();
                }
            }
            else{
                that.localPrize();
            }
        });
    },
    localPrize:function(){
        //本地离线抽奖
        var left_prize_count = this.prize_count - this.current_prize_persons.length, userIds = [], randIndexes = [];//剩余奖品个数
        var that = this;
        if( this.users && this.users.length < left_prize_count ) return false; //剩余人数不够抽奖
        if( this.cut_persons.length > 0 ){
            $.each(that.cut_persons ,function(k,v){
                that.prize_persons.push(v.user_id);
                that.current_prize_persons.push(v);
                userIds.push(v.user_id);
            } );
            left_prize_count = that.prize_count - this.current_prize_persons.length;
        }
        for( var i = 0; i < left_prize_count ; i++ ){
            var j = 0;
            while ( 1 ){
                var ranNum = Math.floor( Math.random() * this.users.length );
                if( $.inArray( this.users[ranNum].user_id , this.prize_persons ) == -1
                    &&
                    $.inArray( ranNum , randIndexes ) == -1 ){
                    randIndexes.push( ranNum );
                    this.prize_persons.push(this.users[ranNum].user_id);
                    this.current_prize_persons.push(this.users[ranNum]);
                    userIds.push(this.users[ranNum].user_id);
                    break;
                }
                if( j++ > 1000 ) break;
            }
        }
        setCookie(this.cookie_key,this.prize_persons.toString());
        this.displayEffect();
        if( that.is_ajax ) return false;
        that.is_ajax = true;
        $.ajax({
            url:that.send_prize_result_url,
            type:"post",
            dataType:"json",
            data:{userIds:userIds},
            error:function(){ that.is_ajax = false; } //网络错误
        }).done(function(data){
            that.is_ajax = false;
        });

    },
    displayEffect:function(){
        //展示获奖用户特效 回调函数
    },
    startRoll:function(){
        var that = this;
        $.ajax({ url:that.start_shake_api, type:"post", dataType:"json", timeout:10000, //3s超时
            data:{}, error:function(){}, complete : function(XMLHttpRequest,status){}
        }).done( function( data ){ if( data.error == 0 ){} else{} } );
    },
    endedRoll:function(){
        var that = this;
        $.ajax({ url:that.close_shake_api, type:"post", dataType:"json", timeout:10000, //3s超时
            data:{}, error:function(){}, complete : function(XMLHttpRequest,status){}
        }).done( function( data ){ if( data.error == 0 ){} else{} } );
    }

};

//写cookies
function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}